package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.entity.Activity;
import com.qk.entity.Clue;
import com.qk.entity.Dept;
import com.qk.management.mapper.ActivityMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.service.ActivityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ClueMapper clueMapper;

    @Override
    public PageResult<Activity> page(Integer channel, Integer type, Integer status, Integer page, Integer pageSize) {
        Integer total = activityMapper.count(channel, type,status);
        Integer offset = (page-1)*pageSize;
        List<Activity> rows = activityMapper.selectPage(channel, type,status,offset,pageSize);
        return PageResult.<Activity>builder()
                .total(total)
                .rows(rows)
                .build();
    }

    @Override
    public void add(Activity activity) {
        log.info("添加活动：{}", activity);
        //参数校验
        boolean hasNullField = BeanUtil.hasNullField(activity, "discount", "voucher", "createTime", "updateTime", "id");
        if (hasNullField) {
            log.error("参数有误");
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        activity.setCreateTime(LocalDateTime.now());
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.insert(activity);
    }

    @Override
    public Activity getById(Integer id) {
        return activityMapper.selectById(id);
    }

    @Override
    public void update(Activity activity) {
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.update(activity);
    }

    @Override
    public void deleteById(Integer id) {
        log.info("删除活动：{}", id);
        // 业务校验，如果当前活动被线索引用则无法删除
        // 根据活动id查询线索
        List<Clue> clues = clueMapper.selectList(Wrappers.lambdaQuery(Clue.class).eq(Clue::getActivityId, id));
        // 如果有线索引用该活动则不能删除
        if (!clues.isEmpty()) {
            log.error("当前活动{}被线索 引用，无法删除", id);
            CommonException.throwCommonException(ParamEnum.ACTIVITY_REFERENCE_ERROR);
        }
        activityMapper.deleteById(id);
    }

    @Override
    public List<Activity> getActivityByType(String type) {
        List<Activity> list =activityMapper.selectByType(type);
        return list;
    }
}
